package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.util.StringUtil;
import com.huaweicloud.sdk.iotda.v5.IoTDAClient;
import com.huaweicloud.sdk.iotda.v5.model.*;
import com.zzyl.common.core.domain.AjaxResult;
import com.zzyl.common.exception.base.BaseException;
import com.zzyl.common.utils.StringUtils;
import com.zzyl.common.utils.uuid.UUID;
import com.zzyl.nursing.dto.DeviceDto;
import com.zzyl.nursing.vo.DeviceDetailVo;
import com.zzyl.nursing.vo.ProductVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.service.IDeviceService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import static com.zzyl.common.constant.CacheConstants.ALL_PRODUCT_KEY;

/**
 * 智能设备Service业务层处理
 *
 * @author alexis
 * @date 2025-10-13
 */
@Service
@Slf4j
public class DeviceServiceImpl extends ServiceImpl<DeviceMapper, Device> implements IDeviceService {
    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private IoTDAClient iotDAClient;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 查询智能设备
     *
     * @param id 智能设备主键
     * @return 智能设备
     */
    @Override
    public Device selectDeviceById(Long id) {
        return deviceMapper.selectById(id);
    }

    /**
     * 查询智能设备列表
     *
     * @param device 智能设备
     * @return 智能设备
     */
    @Override
    public List<Device> selectDeviceList(Device device) {
        return deviceMapper.selectDeviceList(device);

    }

    /**
     * 新增智能设备
     *
     * @param device 智能设备
     * @return 结果
     */
    @Override
    public int insertDevice(Device device) {
        return deviceMapper.insert(device);
    }

    /**
     * 批量删除智能设备
     *
     * @param ids 需要删除的智能设备主键
     * @return 结果
     */
    @Override
    public int deleteDeviceByIds(Long[] ids) {
        return deviceMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 同步产品列表
     */
    @Override
    public void syncProductList() {

        //发起请求
        ListProductsRequest request = new ListProductsRequest();
        request.setLimit(50);
        ListProductsResponse response = iotDAClient.listProducts(request);
        //储存到redis
        redisTemplate.opsForValue().set(ALL_PRODUCT_KEY, JSONUtil.toJsonStr(response.getProducts()));
    }

    /**
     * 获取所有产品列表
     *
     * @return
     */
    @Override
    public List<ProductVo> allProduct() {
        String allProduct = redisTemplate.opsForValue().get(ALL_PRODUCT_KEY);
        if (StringUtil.isEmpty(allProduct)) {
            return Collections.emptyList();
        }
        return JSONUtil.toList(allProduct, ProductVo.class);
    }

    /**
     * 注册设备
     */
    @Override
    public void registerDevice(DeviceDto deviceDto) {
        //校验设备名称是否重复
        Long count = lambdaQuery().eq(Device::getDeviceName, deviceDto.getDeviceName()).count();
        if (count > 0) {
            throw new BaseException("设备名称重复");
        }
        //设备标识是否重复
        count = lambdaQuery().eq(Device::getNodeId, deviceDto.getNodeId()).count();
        if (count > 0) {
            throw new BaseException("设备标识码重复");
        }
        //位置类型为0时，物理位置类型-1
        if (deviceDto.getLocationType() == 0) {
            deviceDto.setPhysicalLocationType(-1);
        }
        //同一位置是否绑定了相同的产品
        count = lambdaQuery()
                .eq(Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .count();
        if (count > 0) {
            throw new BaseException("同一位置已绑定相同产品");
        }
        //设置secret
        String secret = UUID.randomUUID().toString().replaceAll("-", "");
        //注册设备（iotId）
        AddDeviceRequest request = new AddDeviceRequest();
        AddDevice body = new AddDevice();
        body.withNodeId(deviceDto.getNodeId())
                .withDeviceName(deviceDto.getDeviceName())
                .withProductId(deviceDto.getProductKey())
                .withAuthInfo(new AuthInfo().withSecret(secret));
        request.setBody(body);
        AddDeviceResponse response = null;
        try {
            response = iotDAClient.addDevice(request);
        } catch (Exception e) {
            log.error("设备注册失败 - 设备名称: {}, 节点ID: {}, 产品ID: {}",
                    deviceDto.getDeviceName(),
                    deviceDto.getNodeId(),
                    deviceDto.getProductKey(),
                    e);
            // 提供更详细的错误信息
            if (e.getMessage() != null) {
                throw new BaseException("设备注册失败: " + e.getMessage());
            } else {
                throw new BaseException("设备注册失败，请检查华为云IoTDA服务配置和网络连接");
            }
        }
        //本地存储
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        device.setIotId(response.getDeviceId());
        device.setSecret(secret);
        save(device);
    }

    /**
     * 查询设备详细信息
     *
     * @return
     */
    @Override
    public DeviceDetailVo selectAllDevice(String iotId) {
        //查数据库里的设备信息
        Device device = lambdaQuery().eq(Device::getIotId, iotId).one();
        if (device == null) {
            return null;
        }
        //查iotda里的设备信息
        ShowDeviceRequest request = new ShowDeviceRequest();
        request.setDeviceId(iotId);
        ShowDeviceResponse response = null;
        try {
            response = iotDAClient.showDevice(request);
        } catch (Exception e) {
            throw new BaseException("设备不存在");
        }
        //封装返回
        DeviceDetailVo deviceDetailVo = BeanUtil.toBean(device, DeviceDetailVo.class);
        deviceDetailVo.setDeviceStatus(response.getStatus());
        String activeTimeStr = response.getActiveTime();
        if (StringUtils.isNotEmpty(activeTimeStr)) {
            LocalDateTime activeTime = LocalDateTimeUtil.parse(activeTimeStr, DatePattern.UTC_MS_PATTERN);
            //日期时区转换
            activeTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();
            deviceDetailVo.setActiveTime(activeTime);
        }
        return deviceDetailVo;
    }

    /**
     * 查询设备服务属性
     *
     * @param iotId
     * @return
     */
    @Override
    public AjaxResult queryServiceProperties(String iotId) {
        ShowDeviceShadowRequest request = new ShowDeviceShadowRequest();
        request.withDeviceId(iotId);
        ShowDeviceShadowResponse response = null;
        try {
            response = iotDAClient.showDeviceShadow(request);
        } catch (Exception e) {
            log.error("查询设备服务属性失败 - 设备ID: {}", iotId, e);
            throw new BaseException("设备不存在");
        }
        List<DeviceShadowData> shadow = response.getShadow();
        if (CollUtil.isEmpty(shadow)) {
            List<Object> emptyList = Collections.emptyList();
            return AjaxResult.success(emptyList);
        }
        //转换成任意对象
        JSONObject obj = JSONUtil.parseObj(shadow.get(0).getReported().getProperties());
        //创建List
        List<Map<String, Object>> list = new ArrayList<>();
        //处理上报时间日期
        LocalDateTime activeTime = LocalDateTimeUtil.parse(shadow.get(0).getReported().getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
        //日期时区转换
        LocalDateTime eventTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC))
                .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                .toLocalDateTime();
        //封装成Map加入list
        obj.forEach((key, value) -> {
            Map<String, Object> map = new HashMap<>();
            map.put("functionId", key);
            map.put("value", value);
            map.put("eventTime", eventTime);
            list.add(map);
        });
        return AjaxResult.success(list);
    }

    /**
     * 修改智能设备
     *
     * @param deviceDto 智能设备
     * @return 结果
     */
    @Override
    public int updateDevice(DeviceDto deviceDto) {
        UpdateDeviceRequest request = new UpdateDeviceRequest();
        UpdateDevice body = new UpdateDevice();
        Long count = lambdaQuery()
                .eq(deviceDto.getDeviceName() != null, Device::getDeviceName, deviceDto.getDeviceName())
                .ne(Device::getIotId, deviceDto.getIotId())
                .count();
        if (count > 0) {
            throw new BaseException("设备名称已存在");
        }
        //位置类型为0时，物理位置类型-1
        if (deviceDto.getLocationType() == 0) {
            deviceDto.setPhysicalLocationType(-1);
        }
        //查询同一位置已绑定相同产品
        count = lambdaQuery()
                .eq(deviceDto.getBindingLocation() != null, Device::getBindingLocation, deviceDto.getBindingLocation())
                .eq(Device::getLocationType, deviceDto.getLocationType())
                .eq(deviceDto.getProductKey() != null, Device::getProductKey, deviceDto.getProductKey())
                .eq(Device::getPhysicalLocationType, deviceDto.getPhysicalLocationType())
                .ne(Device::getIotId, deviceDto.getIotId())
                .count();

        if (count > 0) {
            throw new BaseException("同一位置已绑定相同产品");
        }
        body.setDeviceName(deviceDto.getDeviceName());
        request.withBody(body);
        request.withDeviceId(deviceDto.getIotId());
        UpdateDeviceResponse response = null;
        try {
            response = iotDAClient.updateDevice(request);
        } catch (
                Exception e) {
            throw new BaseException("修改设备失败");
        }
        Device device = BeanUtil.toBean(deviceDto, Device.class);
        return updateById(device) ? 1 : 0;
    }

    /**
     * 删除智能设备信息
     *
     * @param iotId 智能设备主键
     * @return 结果
     */
    @Override
    public void deleteDeviceById(String iotId) {
        DeleteDeviceRequest request = new DeleteDeviceRequest();
        request.withDeviceId(iotId);
        DeleteDeviceResponse response = iotDAClient.deleteDevice(request);
        if (response.getHttpStatusCode() != 204) {
            log.error("删除设备失败 - 错误码: {};",
                    response.getHttpStatusCode());
            throw new BaseException("删除设备失败");
        }
        lambdaUpdate().eq(Device::getIotId, iotId).remove();
    }

    /**
     * 查询产品信息
     *
     * @param productKey
     * @return
     */
    @Override
    public AjaxResult queryProduct(String productKey) {
        ShowProductRequest request = new ShowProductRequest();
        request.withProductId(productKey);
        ShowProductResponse response = iotDAClient.showProduct(request);
        if(response.getHttpStatusCode() != 200){
            return AjaxResult.error("查询产品信息失败");
        }
        List<ServiceCapability> serviceCapabilities = response.getServiceCapabilities();
        //判断服务列表是否为空
        if(CollUtil.isEmpty(serviceCapabilities)){
            return AjaxResult.success(Collections.emptyList());
        }
        return AjaxResult.success(serviceCapabilities);
    }

}
